package com.jingdianjichi.subject.domin.service.impl;

import com.alibaba.fastjson.JSON;
import com.jingdianjichi.subject.common.entity.PageResult;
import com.jingdianjichi.subject.common.enums.IsDeletedFlagEnum;
import com.jingdianjichi.subject.common.enums.SubjectInfoTypeEnum;
import com.jingdianjichi.subject.domin.convert.SubjectInfoConverter;
import com.jingdianjichi.subject.domin.entity.SubjectInfoBO;
import com.jingdianjichi.subject.domin.handler.subject.SubjectTypeHandler;
import com.jingdianjichi.subject.domin.handler.subject.SubjectTypeHandlerFactory;
import com.jingdianjichi.subject.domin.service.SubjectInfoDomainService;
import com.jingdianjichi.subject.infra.basic.entity.SubjectInfo;
import com.jingdianjichi.subject.infra.basic.entity.SubjectLabel;
import com.jingdianjichi.subject.infra.basic.entity.SubjectMapping;
import com.jingdianjichi.subject.infra.basic.service.SubjectInfoService;
import com.jingdianjichi.subject.infra.basic.service.impl.SubjectLabelServiceImpl;
import com.jingdianjichi.subject.infra.basic.service.impl.SubjectMappingServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 题目相关接口
 * @author 86156
 * @version 1.0
 * @date 2024-10-21 11:50
 */
@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {
    @Autowired
    SubjectInfoService subjectInfoService;
    @Resource
    SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Autowired
    private SubjectMappingServiceImpl subjectMappingService;
    @Autowired
    private SubjectLabelServiceImpl subjectLabelService;

    /**
     * 新增题目
     * @param subjectInfoBO
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBO subjectInfoBO) {
        if(log.isInfoEnabled()){
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBO));
        }
        // 工厂模式+策略模式 实现题目的插入
        // 期望有一个工厂 包含了四种类型 根据传入Type的不同, 动态的去映射处理
        SubjectInfo subjectInfo = SubjectInfoConverter.instance.convertBoToInfo(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);
        subjectInfoBO.setId(subjectInfo.getId());
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        handler.add(subjectInfoBO);

        // 处理标签,分类与题目的对应关系  标签和分类是多对多的一种关系
        List<Long> categoryIds = subjectInfoBO.getCategoryIds();
        List<Long> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> mappingList = new LinkedList<>();
        categoryIds.forEach(category->{
            labelIds.forEach(label->{
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfoBO.getId());
                subjectMapping.setCategoryId(category);
                subjectMapping.setLabelId(label);
                subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                mappingList.add(subjectMapping);
            });
        });
        subjectMappingService.insertBatch(mappingList);
    }

    /**
     * 题目分页查询
     * @param subjectInfoBO
     * @return
     */
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        // 分页开始的位置
        int start = (subjectInfoBO.getPageNo()-1)*subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConverter.instance.convertBoToInfo(subjectInfoBO);
        // 查询得到总数量
        int count = subjectInfoService.countByCondition(subjectInfo,
                subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId());
        if(count == 0){
            return pageResult;
        }
        // 进行分页查询
        List<SubjectInfo> infoList = subjectInfoService.queryPage(subjectInfo,
                subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId(),start,subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfoBOS = SubjectInfoConverter.instance.convertInfoListToBOList(infoList);
        // 给返回结果中添加数据
        pageResult.setRecords(subjectInfoBOS);
        pageResult.setTotal(count);
        return pageResult;
    }

    /**
     * 查询题目信息
     * @param subjectInfoBO
     * @return
     */
    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBO.getId());
        // 通过策略模式获取处理的handler
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectInfoBO query = handler.query(subjectInfo.getId());
        query.setSubjectName(subjectInfo.getSubjectName());
        query.setSubjectType(subjectInfo.getSubjectType());
        query.setSubjectDifficult(subjectInfo.getSubjectDifficult());
        query.setSubjectScore(subjectInfo.getSubjectScore());
        query.setSubjectParse(subjectInfo.getSubjectParse());
        query.setId(subjectInfo.getId());

        // 查询标签名称集合
        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

        // 从题目映射表中查询出标签id集合
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        List<Long> labelIdlist = mappingList.stream().map(SubjectMapping::getLabelId).
                collect(Collectors.toList());

        // 查询标签实体集合,拿出标签名称加入labelNameList中
        List<SubjectLabel> labels = subjectLabelService.batchQueryById(labelIdlist);
        List<String> labelNameList = labels.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        query.setLabelNames(labelNameList);
        return query;
    }
}
